package com.vast.ui.component.socketinterface.server.newio;

import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.vast.ui.component.socketinterface.request.RequestQueue;
import com.vast.ui.component.state.Sequence;
import com.vast.ui.component.util.ConsoleLoggerSingleton;
import com.vast.ui.component.util.Logger;

public class ReceiveService implements SocketService {
	 //private final ExecutorService executorService = Executors.newCachedThreadPool();
	 private final ExecutorService executorService = Executors.newSingleThreadExecutor();
	 private ServerSocketChannel   serverSocketChannel;
	 private final Sequence        sequence;
	 private final RequestQueue    receivedQueue;
	 private final Logger          logger;
	 
	 public ReceiveService(Sequence sequence, RequestQueue  receivedQueue) {
		 this.sequence      = sequence;
	     this.receivedQueue = receivedQueue;
	     this.logger        = ConsoleLoggerSingleton.getInstance();
	 }

     public void run() {
         if (serverSocketChannel.isOpen()) {
             try {
                 SocketChannel socketChannel = serverSocketChannel.accept();
                 logger.writeEntry("Receive socket is accepted.");
                 executorService.execute(new ReceiveHandler(socketChannel, sequence, receivedQueue));
             } catch (Exception e) {
                 e.printStackTrace();
             }
         }
     }
     
     public void startup(int port) {
         if (serverSocketChannel == null || !serverSocketChannel.isOpen()) {
             try {
                 serverSocketChannel = ServerSocketChannel.open();
                 serverSocketChannel.socket().bind(new InetSocketAddress(port));
                 new Thread(this).start();
                 logger.writeEntry("Start Receive Service.");
             } catch (Exception e) {
                 try {
                     serverSocketChannel.close();
                 } catch (Exception e2) {}
                 logger.writeEntry("Can not launch Receive Service.");
             }
         } else {
        	 logger.writeEntry("Receive Service is runnning.");
         }
     }
     
     public void shutdown() {
         if (serverSocketChannel != null && serverSocketChannel.isOpen()) {
             try {
                 serverSocketChannel.close();
                 logger.writeEntry("Receive channel is stopped.");
             } catch (Exception e) {}
         } else {
        	 logger.writeEntry("Receive channel is not working.");
         }
     }
	 
}
